package com.tianji.remark.service.impl;

import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.entity.dto.LikeRecordFormDTO;
import com.tianji.remark.entity.dto.LikedTimesDTO;
import com.tianji.remark.entity.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author lemon
 */
@Slf4j
//@Service
//@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private RabbitMqHelper mqHelper;


    /**
     * 新增取消点赞记录
     *
     * @param dto
     */
    @Override
    public void saveLikedRecord(LikeRecordFormDTO dto) {
        Long userId = UserContext.getUser();
        Long bizId = dto.getBizId();
        if (userId == null || bizId == null) {
            throw new IllegalArgumentException("参数错误");
        }
        boolean flag = true;
        if (dto.getLiked()) {
            // 点赞
            flag = liked(dto, userId);
        } else {
            // 取消点赞
            flag = unliked(dto, userId);
        }
        if (!flag) {
            // 说明点赞或者取消点赞失败
            // 就是已经点过赞了
            return;
        }

        // 统计该业务下的总的点赞数
        Integer likeRecordCountTotal = this.lambdaQuery().eq(LikedRecord::getBizId, bizId).count();

        LikedTimesDTO likedTimesDTO = new LikedTimesDTO();
        likedTimesDTO.setBizId(bizId);
        likedTimesDTO.setLikedTimes(likeRecordCountTotal);
        // 发送消息
        log.info("发送点赞消息,消息内容:{}", likedTimesDTO);
        mqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, dto.getBizType()),
                likedTimesDTO
                // 也可以使用builder模式
                // LikedTimesDTO.builder().bizId().likedTimes().build()
        );

    }

    /**
     * 批量查询点赞状态
     *
     * @param bizIds
     * @return
     */
    @Override
    public Set<Long> getLikesStatus(List<Long> bizIds) {
        if (CollUtils.isEmpty(bizIds)) {
            return CollUtils.emptySet();
        }
        // 1.获取当前用户
        Long userId = UserContext.getUser();
        // 2.查询当前用户是否点赞了这些业务
        List<LikedRecord> list = this.lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .in(LikedRecord::getBizId, bizIds)
                .list();
        // 没有的话就是空
        if (list == null || list.isEmpty()) {
            return CollUtils.emptySet();
        }
        // 3.将查询到的转为BizId的set集合
        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
    }

    @Override
    public Set<Long> getLikesStatusForRedis(List<Long> bizIds) {
        return null;
    }

    @Override
    public void readLikedTimesAndMessage(String bizType, int maxBizSize) {

    }

    @Override
    public void syncLikedDataFromRedisToDB() {

    }

    /**
     * 点赞
     *
     * @param dto
     * @param userId
     * @return
     */
    private boolean liked(LikeRecordFormDTO dto, Long userId) {
        LikedRecord record = this.lambdaQuery().eq(LikedRecord::getBizId, dto.getBizId())
                .eq(LikedRecord::getUserId, userId)
                .one();
        // 说明已经点过赞了
        if (record != null) {
            return false;
        }
        // 如果为null 则说明没有点过赞，添加记录
        LikedRecord likedRecord = BeanUtils.copyBean(dto, LikedRecord.class);
        likedRecord.setUserId(userId);
        // 看保存是否成功
        return this.save(likedRecord);
    }

    /**
     * 取消点赞
     *
     * @param dto
     * @param userId
     * @return
     */
    private boolean unliked(LikeRecordFormDTO dto, Long userId) {
        LikedRecord record = this.lambdaQuery().eq(LikedRecord::getBizId, dto.getBizId())
                .eq(LikedRecord::getUserId, userId)
                .one();
        // 没有点过赞，直接返回false
        if (record == null) {
            // 说明没有点过赞
            return false;
        }
        // 删除记录
        // 看删除是否成功
        return this.removeById(record.getId());
    }
}
